package com.liesheng.haylou.utils;

import android.content.Context;

import com.liesheng.haylou.app.HyApplication;

/**
 * Date:2019/11/20
 * <p>
 * Author:wuzhiguang
 * <p>
 * Description:
 */
public class NumUtil {

    /*  hexStr形如：1A,不包括十六进制前面的Ox
       没判断是否字符串
   */
    public static int hex2Int(String hexStr) {
        int result = 0;
        char[] hex = hexStr.toCharArray();
        for(int i = 0; i < hex.length; i++){
            if(getHexValue(hex[i]) != -1){
                result += getHexValue(hex[i]) * Math.pow(16, hex.length-i-1);
            }
            else {
                return 0;
            }
        }
        return result;
    }


    /**
     * byte数组转化为string
     */
    static final char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    /**
     * hex转byte数组
     * @param hex
     * @return
     */
    public static byte[] hexToBytes(String hex){
        int m = 0, n = 0;
        int byteLen = hex.length() / 2; // 每两个字符描述一个字节
        byte[] ret = new byte[byteLen];
        for (int i = 0; i < byteLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
            ret[i] = Byte.valueOf((byte)intVal);
        }
        return ret;
    }


    /**
     * 获取十六进制字符ch的int值，如A：10，F：15，9：9
     */
    private static int getHexValue(char ch){
        if(ch >= '0' && ch <= '9'){
            return Integer.parseInt(String.valueOf(ch));
        }
        if ( (ch >= 'a'  && ch <= 'f') || (ch >= 'A' && ch <= 'F')) {
            switch (ch) {
                case 'a':
                case 'A':
                    return 10;
                case 'b':
                case 'B':
                    return 11;
                case 'c':
                case 'C':
                    return 12;
                case 'd':
                case 'D':
                    return 13;
                case 'e':
                case 'E':
                    return 14;
                case 'f':
                case 'F':
                    return 15;
            }
        }
        return 0;
    }
}
